const api = require("../../utils/apiUtils");
const app = getApp();

Page({
  data: {
    tabBar:[
      {key:'全部',pox:-280},
      {key:'充电插座',pox:-110},
      {key:'充电宝',pox:60},
      {key:'便携电池',pox:230},
    ],
    mapCfg:{
      scale: 14,
      latitude: 30.266786,
      longitude: 120.10675
    }
  },
  mapTap(e) {
    console.log('mapTap',e);
  },
  mapMarkerTap(e) {
    console.log('mapMarkerTap', e);
  },
  /**
   * 获取附近网点信息
   */
  _findNearby(latitude,longitude){
    const self = this;
    const markers = [];
    api.post(api.url.commonNearPlace,{
        longitude:longitude,
        latitude:latitude,
        limit:10
    },res=>{
        console.log(res)
        if(res.data.code==200){
            for (const item of res.data.body.items) {
                markers.push({
                    id:item.placeId,
                    latitude:item.latitude,
                    longitude:item.longitude,
                    width:30,height:30,
                    iconPath:'/static/icon/icon.png',
                })
            }
            this.mapCtx.updateComponents({
              'markers':markers
            })

            self.setData({
                markers:markers,
                nearPlace:res.data.body.items||[]
            })
        }
    })
  },
  btnChangeTab(e){
    this.setData({
        tabBarIndex:e.currentTarget.dataset.index
    })
    if (!my.canIUse('createMapContext.return.updateComponents')) {
      my.alert({ 
        title: '客户端版本过低',
        content: 'this.mapCtx.updateComponents 需要 10.1.35 及以上版本'
      });
      return;
    }
    let mapCfg = this.data.mapCfg;
    this._findNearby(mapCfg.latitude,mapCfg.longitude)
  },
  onLoad() {
    my.getLocation({
      type: 1, // 获取经纬度和省市区县数据
      success: (res) => {
        console.log(res);
        let mapCfg = this.data.mapCfg;
        mapCfg.latitude = res.latitude;
        mapCfg.longitude = res.longitude;
        this.setData({mapCfg})
      },
      fail: (error) => {
        console.error('定位失败: ', JSON.stringify(error));
      },
      complete: (res) => {
        //console.log(res);
      },
    });
  },
  onReady() {
    // 使用 my.createMapContext 获取 map 上下文
    this.mapCtx = my.createMapContext('map');
  },
});
